<template>
  <el-card class="form-container" shadow="never">
    <el-form
      :model="guide"
      :rules="rules"
      ref="guideFrom"
      label-width="150px"
      size="small">
      <el-form-item label="标题：" prop="title">
        <el-input v-model="guide.title" class="input-width" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="发布者：" prop="source">
        <el-input v-model="guide.source" class="input-width" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="所属社区：" prop="communityId">
        <el-select
          v-model="guide.communityId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading"
          @change="communityChange">
          <el-option
            v-for="item in communityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动地址：" prop="addr">
        <el-input v-model="guide.addr" class="input-width" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="封面：" prop="image">
        <single-upload v-model="guide.image" tip="提示：请上传 690x278（Px）尺寸的图片，大小不超过500K。"></single-upload>
      </el-form-item>
      <el-form-item
        label="正文："
        prop="content"
        required
      >
        <div
          ref="editor"
          class="editor-wrapper"
        ></div>
      </el-form-item>
      <el-form-item label="渠道：" prop="channel">
        <el-select v-model="guide.channel" placeholder="请选择">
          <el-option
            v-for="item in channelTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否需要报名：" prop="isAppointment">
        <el-select v-model="guide.isAppointment" placeholder="请选择">
          <el-option
            v-for="item in isAppointmentTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报名期限：" prop="dateRange">
        <el-date-picker
          v-model="guide.applyDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="报名人数：" prop="registration">
        <el-input v-model="guide.registration" class="input-width" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="活动期限：" prop="dateRange">
        <el-date-picker
          v-model="guide.activityDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit('guideFrom')">提交</el-button>
        <!--<el-button v-if="!isEdit" @click="resetForm('courseFrom')">重置</el-button>-->
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import SingleUpload from '@/components/Upload/singleUpload'
import WEditor from 'wangeditor'
import moment from 'moment'
import { umsCommunityList, RcRegistrationContentControllerSave, RcRegistrationContentControllerFindOne, RcRegistrationContentControllerUpdate } from '@/api/neighbour'

const defaultGuide = {
  classified: '01',
  title: '',
  source: '',
  mobile: '',
  image: '',
  channel: '',
  content: '',
  isAppointment: '',
  registration: '',
  applyDateRange: [new Date(), new Date('2099-12-31')],
  activityDateRange: [new Date(), new Date('2099-12-31')]
}
export default {
  name: 'Detail',
  components: { SingleUpload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      guide: {},
      communityOptions: [],
      channelTypeOptions: [{ label: 'APP', value: '1' }, { label: '小程序', value: '2' }, { label: 'H5', value: '3' }],
      isAppointmentTypeOptions: [{ label: '否', value: '0' }, { label: '是', value: '1' }],
      loading: false,

      rules: {
        title: [
          { required: true, message: '请输入', trigger: 'blur' }
          // { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        source: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        communityId: [
          { required: true, message: '请选择', trigger: 'blur' }
        ],
        addr: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请选择课程封面', trigger: 'blur' }
        ],
        channel: [
          { required: true, message: '请选择', trigger: 'blur' }
        ],
        isAppointment: [
          { required: true, message: '请选择', trigger: 'blur' }
        ]
        // applyDateRange: [
        //   {
        //     type: 'array',
        //     required: true,
        //     message: '请选择日期',
        //     trigger: 'blur'
        //   }
        // ],
        // activityDateRange: [
        //   {
        //     type: 'array',
        //     required: true,
        //     message: '请选择日期',
        //     trigger: 'blur'
        //   }
        // ]
      }
    }
  },
  mounted () {
    if (this.isEdit) {
      RcRegistrationContentControllerFindOne({ id: this.$route.query.id }).then(response => {
        const { classified, title, source, communityId, addr, image, channel, content, isAppointment, stime, etime, registration, sregistration, eregistration } = response.data

        this.communityOptions = [{ value: response.data.communityId, label: response.data.communityName }]
        this.guide = {
          classified,
          title,
          source,
          communityId,
          addr,
          image,
          channel,
          content,
          isAppointment,
          registration,
          applyDateRange: [sregistration || null, eregistration || null],
          activityDateRange: [stime, etime]
        }
        this.initEditor(this.guide.content)
      })
    } else {
      this.guide = Object.assign({}, defaultGuide)
      this.initEditor('')
    }
  },
  methods: {
    initEditor (content) {
      this.editor = new WEditor(this.$refs.editor)
      // this.editor.customConfig.debug = true
      this.editor.customConfig.uploadImgServer = '/zdmanage/upload'
      this.editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024
      // this.editor.customConfig.uploadImgParams = {
      //   busiType: 'rich'
      // }
      this.editor.customConfig.customAlert = function (info) {
        // message.error(info)
      }
      this.editor.customConfig.uploadFileName = 'file'
      this.editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result) {
          if (!result.data) {
            // message.error(result.resultMessage)
          } else {
            insertImg(result.data)
          }
        }
      }
      this.editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        // 'link', // 插入链接
        // 'list', // 列表
        'justify', // 对齐方式
        // 'quote', // 引用
        // 'emoticon', // 表情
        'image', // 插入图片
        // 'table', // 表格
        // 'video', // 插入视频
        // 'code', // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ]
      // this.editor.customConfig.onchange = (html) => {
      //   this.editorContent = html
      //   this.$emit('change', this.editorContent)
      // }
      this.editor.create()
      this.editor.txt.html(content)
    },
    remoteMethod (query) {
      // 来源机构
      if (query !== '') {
        this.loading = true
        umsCommunityList({ pageSize: 50, pageNum: 1, communityName: query }).then(response => {
          this.loading = false
          this.communityOptions = response.data.list.map(item => {
            return { value: item.id, label: item.communityName }
          })
        })
      } else {
        this.communityOptions = []
      }
    },
    communityChange (communityId) {
      this.guide.communityId = communityId
      this.communityOptions.map((item) => {
        if (item.value === communityId) {
          this.guide.communityName = item.label
        }
      })
    },
    onSubmit (formName) {
      this.guide.content = this.editor.txt.html()
      // if (!this.guide.content) {
      //   return this.$message({
      //     message: '请输入正文',
      //     type: 'error',
      //     duration: 1000
      //   })
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = {
              ...this.guide
            }

            params.stime = moment(this.guide.activityDateRange[0]).format()
            params.etime = moment(this.guide.activityDateRange[1]).format()
            if (this.guide.applyDateRange) {
              params.sregistration = moment(this.guide.applyDateRange[0]).format()
              params.eregistration = moment(this.guide.applyDateRange[1]).format()
            } else {
              params.sregistration = ''
              params.eregistration = ''
            }

            delete params.activityDateRange
            delete params.applyDateRange

            if (this.isEdit) {
              params.id = this.$route.query.id
              RcRegistrationContentControllerUpdate(params).then(res => {
                if (res.code === 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                    duration: 1000
                  })
                  this.$router.back()
                } else {
                  this.$message({
                    message: res.message,
                    type: 'error',
                    duration: 1000
                  })
                }
              })
            } else {
              RcRegistrationContentControllerSave(params).then(res => {
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            }
          })
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.guide = Object.assign({}, defaultGuide)
    },
    back () {
      this.$router.go(-1)
    }
  }

}
</script>
<style scoped>
  .input-width {
    width: 70%;
  }
  .editor-wrapper{
    position: relative;
    z-index: 2;
  }
</style>
